import { useState, useEffect } from 'react'
import Hoc_login from "@/utils/Hoc_login"
import {
  Space,
  Table,
  Popconfirm,
  message,
  Modal,
  Button,
  Input,
  Form,
  Pagination,
  Radio,
  Select,
  Upload,
  Drawer,
  Descriptions
} from 'antd';
import type { TableProps, DescriptionsProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from '@/utils/Request'
import { deleteHouse, addHouse, editHouse, getHouse, deleteSecondHouse } from '@/api';
import city from "@/data/city.json"


function Index() {
  const { Option } = Select;

  const normFile = (e: any) => {
    console.log('上传成功！', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };


  // 表格数据
  const [table, setTable] = useState([])
  // 模态窗口
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 请求数据时loading状态
  const [load, setLoad] = useState(true)
  //1：新房，2：二手房 3：出租房
  const [houseType, setHouseType] = useState(1)
  // 当前页码
  const [currentPage, setCurrentPage] = useState(1)
  // 总条数
  const [length, setLength] = useState()
  // 默认标题为空
  const [modelTitle, setModelTitle] = useState("")
  // 默认id
  const [id, setId] = useState()
  // 三级联动数据
  const [provinceData, setProvinceData] = useState(city)
  const [cityData, setCityData] = useState(city[0].children)
  const [cityItem, setCityItem] = useState(city[0].children[0].code)
  const [areaData, setAreaData] = useState(cityData[0].children)
  const [areaItem, setAreaItem] = useState(cityData[0].children[0].code)
  // 搜索框数据
  const [wen, setWen] = useState("")
  const [search, setSearch] = useState("")
  const [open, setOpen] = useState(false);
  const [data, setData]: any = useState([])


  // 新增按钮
  const showModal = () => {
    setIsModalOpen(true);
    setModelTitle("新增数据")
  };

  // // 窗口确认
  // const handleOk = () => {
  //   setIsModalOpen(false);
  // };

  // // 窗口取消
  // const handleCancel = () => {
  //   setIsModalOpen(false);
  // };

  // 依赖监听
  useEffect(() => {
    // const url = houseType == 1 ? '/housing' : '/second/housing'
    // axios.get(url, { params: { currentPage } }).then((res: any) => {
    //   // console.log(res)
    //   setTable(res.data.data.map((item: any) => {
    //     item.key = item.id
    //     return item
    //   }))
    //   setLength(res.data.total)
    //   setLoad(false)
    // })
    if (houseType == 1) {
      axios.get("/housing", { params: { currentPage } }).then((res: any) => {
        setTable(res.data.data.map((item: any) => {
          item.key = item.id
          return item
        }))
        setLength(res.data.total)
        setLoad(false)
      })
    } else if (houseType == 2) {
      axios.get("/second/housing", { params: { currentPage } }).then((res: any) => {
        setTable(res.data.data)
        setLoad(false)
      })
    } else {
      axios.get("/second/housing", { params: { currentPage } }).then((res: any) => {
        setTable(res.data.data)
        setLoad(false)
      })
    }
  }, [houseType, currentPage])

  // tab房源切换事件
  const tabCut = (e: any) => {
    setHouseType(e.target.value)
  };

  // 点击下面的分页按钮触发
  const pageChange = (currentPage: any) => {
    setCurrentPage(currentPage)
  }

  // 指定经纪人
  const Broker = () => {

  }


  // 删除数据
  const confirm = async (obj: any) => {
    if (houseType == 1) {
      //新房售卖
      let res = await deleteHouse(obj.id)
      // console.log(obj.id)
      // console.log(res)
      message.success(res.data.message)
      // 重新调用后端数据渲染数据
      let res2 = await axios.get("/housing")
      setTable(res2.data.data)
    } else {
      let res = await deleteSecondHouse(obj.id)
      message.success(res.data.message)
    }


  };

  // 取消删除
  const cancel = (e: any) => {
    console.log(e);
    message.error('取消删除');
  };

  interface DataType {
    key: string;
    name: string;
    price: number;
    update_time: any;
    broker: string;
  }

  const handleOk = () => {
    setIsModalOpen(false);
    form.resetFields()
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields()
  };

  type FieldType = {
    "toward": "string",
    "subway": "string",
    "lift": "string",
    "house_type": "string",
    "way": "string",
    "img": "string",
    "price": 0,
    "broker": "string",
    "ll": "string",
    "building_type": "string",
    "section": "string",
    "extent": "string",
    "name": "string",
    "brand": "string",
    "periods": "string",
    "area": "string",
    "feature": "string",
    "resident": "string",
    "useto": "string",
    "pay": "string",
    "lease": "string",
    "renovation": "string",
    "status": 0,
    "position": "string"
  }

  const [form] = Form.useForm()

  // 提交表单,新增数据
  const onFinish = async (values: any) => {
    // 如果title=="新增数据",调用新增接口，否则调用修改接口
    const formData = form.getFieldsValue()
    if (modelTitle == "新增数据") {
      // 新增数据
      let res = await addHouse(values)
      message.success(res.data.message)
      let res2 = await axios.get("/housing")
      setTable(res2.data.data)
    } else {
      // 编辑数据
      let res = await editHouse({ ...formData, id: id })
      // console.log("185-----------", res)
      message.success(res.data.message)
      let res2 = await getHouse(values)
      // console.log("188++++++++++++++++", res2);
      setTable(res2.data.data)
    }
    // 重置表单
    form.resetFields();
    // 关闭弹窗
    setIsModalOpen(false)
  };

  // 编辑数据
  const Edit = (obj: any) => {
    setId(obj.id)
    // console.log("200----------", obj)
    setIsModalOpen(true)
    setModelTitle("编辑数据")
    obj.img = [obj.img]
    form.setFieldsValue(obj)
    form.setFieldsValue({
      id: { ...obj.id }
    })
  }



  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '楼盘名称',
      dataIndex: 'name',
    },
    {
      title: '详细地址',
      dataIndex: 'area',
    },
    {
      title: '价格',
      dataIndex: 'price',
      render: (text) => <span>{text}/m²</span>,
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
    },
    {
      title: '经纪人',
      dataIndex: 'broker',
      render: (text) => <a onClick={Broker}>{text}</a>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: any) => (
        <Space size="middle">
          <a onClick={() => Detail(record)}>详情</a>
          <a onClick={() => Edit(record)}>编辑</a>
          <Popconfirm
            title=""
            description="你确认删除吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 三级联动事件
  const handleProvinceChange = (value: any) => {
    console.log("273--------------code码:", value)
    const index = provinceData.findIndex((item) => { return item.code == value })
    setCityData(city[index].children)
    setCityItem(city[index].children[0].code)
    setAreaData(city[index].children[0].children)
    setAreaItem(city[index].children[0].children[0].name)
    setWen(city[index].children[0].children[0].name)
    if (value === "00") {
      setWen("")
    }
  };
  const onSecondCityChange = (value: any) => {
    const index = cityData.findIndex((item) => { return item.code == value })
    setCityItem(value)
    setAreaData(cityData[index].children)
    setAreaItem(cityData[index].children[0].name)
    setWen(cityData[index].children[0].name)
  };
  const onAreaChange = (value: any) => {
    const index = areaData.findIndex((item) => { return item.code == value })
    // console.log("***********区县下标：", index)
    setWen(areaData[index].name)
    setAreaItem(value)
  }

  // 搜索事件
  const Search = async () => {
    let res = await getHouse({ area: wen, name: search })
    console.log("302*****************", res)

    if (res.data.code == 1) {
      setTable(res.data.data)
    } else {
      message.warning(res.data.msg)
      setTable(res.data.data)
    }
  }

  // 输入框onChange事件
  const inpValue = (e: any) => {
    // console.log("314***************", e.target.value)
    setSearch(e.target.value)
  }

  // 查看详情页
  const Detail = (obj: any) => {
    setOpen(true)
    setData(obj)
  }
  const onClose = () => {
    setOpen(false)
  }
  // 详情页数据
  const borderedItems: DescriptionsProps['items'] = [
    {
      key: '1',
      label: '序号',
      children: data.id,
    },
    {
      key: '2',
      label: '楼盘名称',
      children: data.name,
    },
    {
      key: '3',
      label: '详细地址',
      children: data.area,
    },
    {
      key: '4',
      label: '价格',
      children: data.price,
    },
    {
      key: '5',
      label: '更新时间',
      children: data.update_time,
    },
    {
      key: '6',
      label: '位置',
      children: data.section,
    },
    {
      key: '7',
      label: '合约',
      children: data.lease,
    },
    {
      key: '8',
      label: '房型',
      children: data.building_type,
    },
    {
      key: '9',
      label: '状态',
      children: data.status,
    },
    {
      key: '10',
      label: '图片',
      children: (
        <>
          <img src={data.img} alt="" style={{ width: '95%' }} />
        </>
      ),
    },
  ]


  return (
    <>
      <div>
        <p>房源管理</p>

        {/* 房源切换 */}
        <Radio.Group defaultValue="1" buttonStyle="solid" onChange={tabCut}>
          <Radio.Button value="1">新房售卖</Radio.Button>
          <Radio.Button value="2">二手房售卖</Radio.Button>
          <Radio.Button value="3">房屋租赁</Radio.Button>
        </Radio.Group><br /><br />

        {/* 三级联动 */}
        <Space wrap size={20}>
          <Select
            defaultValue={city[0].code}
            style={{ width: 200 }}
            onChange={handleProvinceChange}
            options={provinceData.map((province) => ({ label: province.name, value: province.code }))}
          />
          <Select
            style={{ width: 200 }}
            value={cityItem}
            onChange={onSecondCityChange}
            options={cityData.map((city) => ({ label: city.name, value: city.code }))}
          />
          <Select
            style={{ width: 200 }}
            value={areaItem}
            onChange={onAreaChange}
            options={areaData.map((area) => ({ label: area.name, value: area.code }))}
          />
          <Input placeholder='关键字' onChange={inpValue} />
          <Button type='primary' style={{ width: 120, backgroundColor: '#169BD5' }} onClick={() => Search()}>搜索</Button>
        </Space><br /><br />

        {/* 新增按钮 */}
        <Button type="primary" onClick={showModal}>新增</Button>

        <Modal title={modelTitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
          <Form
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 26 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            form={form}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="楼盘名称"
              name="name"
              rules={[{ required: true, message: '数据不能为空!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item<FieldType>
              label="地址"
              name="area"
              rules={[{ required: true, message: '数据不能为空!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item<FieldType>
              label="小区"
              name="resident"
              rules={[{ required: true, message: '数据不能为空!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item<FieldType>
              label="价格"
              name="price"
              rules={[{ required: true, message: '数据不能为空!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item<FieldType>
              name="broker"
              label="指派经纪人"
              hasFeedback
              rules={[{ required: true, message: '数据不能为空!' }]}
            >
              <Select style={{ width: 100, margin: '0 8px' }}>
                <Option value="周丽">周丽</Option>
                <Option value="时瀚">时瀚</Option>
              </Select>
            </Form.Item>
            <Form.Item<FieldType> name="house_type" label="室内" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="一居">一居</Radio>
                <Radio value="二居">二居</Radio>
                <Radio value="三居">三居</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="status" label="房屋状态" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="正常">正常</Radio>
                <Radio value="异常">异常</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="feature" label="入住" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="新上">新上</Radio>
                <Radio value="随时看房">随时看房</Radio>
                <Radio value="押一付一">押一付一</Radio>
                <Radio value="拎包入住">拎包入住</Radio>
                <Radio value="VR看房">VR看房</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="periods" label="楼型" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="经济房">经济房</Radio>
                <Radio value="其他">其他</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="ll" label="楼层" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="底楼层">底楼层</Radio>
                <Radio value="中楼层">中楼层</Radio>
                <Radio value="高楼层">高楼层</Radio>
                <Radio value="顶层">顶层</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="renovation" label="装修程度" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="精装房">精装房</Radio>
                <Radio value="普通装修">普通装修</Radio>
                <Radio value="毛坯房">毛坯房</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="toward" label="房屋朝向" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="东">东</Radio>
                <Radio value="西">西</Radio>
                <Radio value="南">南</Radio>
                <Radio value="北">北</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="useto" label="房屋类型" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="商业楼">商业类</Radio>
                <Radio value="公房">公房</Radio>
                <Radio value="别墅">别墅</Radio>
                <Radio value="四合院">四合院</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="building_type" label="房屋结构类型" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="板楼">板楼</Radio>
                <Radio value="塔楼">塔楼</Radio>
                <Radio value="板塔结合">板塔结合</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="lift" label="电梯" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="有电梯">有电梯</Radio>
                <Radio value="无电梯">无电梯</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="pay" label="租型" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="合租">合租</Radio>
                <Radio value="整租">整租</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="way" label="租赁时间交款" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="季付">季付</Radio>
                <Radio value="月付">月付</Radio>
                <Radio value="年付">年付</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType> name="lease" label="租赁时间" rules={[{ required: true, message: '数据不能为空!' }]}>
              <Radio.Group>
                <Radio value="4-6个月">4-6个月</Radio>
                <Radio value="1-3个月">1-3个月</Radio>
                <Radio value="年租">年租</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item<FieldType>
              name="img"
              label="上传房屋图片"
              valuePropName="fileList"
              getValueFromEvent={normFile}
              rules={[{ required: true, message: '数据不能为空!' }]}
            >
              <Upload name="img" action="https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188" listType="picture">
                <Button icon={<UploadOutlined />}>上传图片</Button>
              </Upload>
            </Form.Item>
            {/* 提交按钮 */}
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type='primary' htmlType='submit'>确认</Button>
            </Form.Item>
          </Form>
        </Modal>
      </div >


      {/* 表格 */}
      < Table columns={columns} dataSource={table} scroll={{ x: 1000, y: 300 }
      } pagination={false} loading={load} />

      {/* 详情页 */}
      <Drawer onClose={onClose} open={open} width={"50%"} closable={false}>
        <Descriptions
          bordered
          title="查看详情"
          items={borderedItems}
        />
      </Drawer>

      {/* 分页 */}
      < Pagination defaultCurrent={1} total={length} onChange={pageChange} />
    </>
  )
}

export default Hoc_login(Index)
